from django.shortcuts import render, render_to_response, redirect

from django.http import HttpResponse, HttpResponseNotFound
from django.template import RequestContext, loader

from datetime import datetime

import json as json2

_NUM_BACKGROUNDS = 3

# to set cookies in IE
def _setP3P( response ):
	response["P3P"] = 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'

def template( template = None ):
	def template_inner( view ):
		def response( *args, **kwargs ):		
	
			args_list = list( args )
			
			request = args[ 0 ]
			del args_list[ 0 ]	
	
			request, result = view( request, *args_list, **kwargs )		

			req = request.REQUEST

			# update background index
			bi = datetime.now().day % _NUM_BACKGROUNDS + 1
			result.update( background_index = bi )
			
			if 'next_section' in req:
				result.update( next_section = req[ 'next_section' ] )
	
			if type( result ) == dict:
				" Result is out. "
				t = loader.get_template( template )
				c = RequestContext( request, result )
	
				response = HttpResponse(	t.render(c),
		        							content_type = 'text/html' )			
	
			elif type( result ) == type( None ):
				response = HttpResponseNotFound( request )	        							
			else:
				response = redirect( result )
	
			_setP3P( response )
			
			return response

		return response

	return template_inner

def json( view ):
	def response( *args, **kwargs ):
		request, data = view( *args, **kwargs )

		response = HttpResponse(	json2.dumps( data ),
								content_type = 'application/json' )

		_setP3P( response )
		
		return response

	return response
		